{% extends "base_config.html" %}
{% block content %}
<div class="page">
    <div class="section">
        <h2 class="section-title">
            <img class="card-icon" src="/static/assets/icons/{{ content_type }}.svg" alt="{{ content_type|capitalize }}">
            <span class="card-title-text">{{ content_type|capitalize }}</span>
        </h2>
        <form id="config-form">
            <table>
                <tr>
                    <td>
                        <label for="input-files" title="Add a {{content_type}} file for Khoj to index">Files</label>
                    </td>
                    <td id="input-files-cell">
                        {% if current_config['input_files'] is none %}
                            <input type="text" id="input-files" name="input-files" placeholder="~\Documents\notes.{{content_type}}">
                        {% else %}
                            {% for input_file in current_config['input_files'] %}
                                <input type="text" id="input-files" name="input-files" value="{{ input_file }}" placeholder="~\Documents\notes.{{content_type}}">
                            {% endfor %}
                        {% endif %}
                    </td>
                    <td>
                        <button type="button" id="input-files-button">Add</button>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="input-filter" title="Add a folder with {{content_type}} files for Khoj to index">Folders</label>
                    </td>
                    <td id="input-filter-cell">
                        {% if current_config['input_filter'] is none %}
                            <input type="text" id="input-filter" name="input-filter" placeholder="~/Documents/{{content_type}}">
                        {% else %}
                            {% for input_filter in current_config['input_filter'] %}
                                <input type="text" id="input-filter" name="input-filter" placeholder="~/Documents/{{content_type}}" value="{{ input_filter.split('/*')[0] }}">
                            {% endfor %}
                        {% endif %}
                    </td>
                    <td>
                        <button type="button" id="input-filter-button">Add</button>
                    </td>
                </tr>
            </table>

            <table style="display: none;" >
                <tr>
                    <td>
                        <label for="compressed-jsonl">Compressed JSONL (Output)</label>
                    </td>
                    <td>
                        <input type="text" id="compressed-jsonl" name="compressed-jsonl" value="{{ current_config['compressed_jsonl'] }}">
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="embeddings-file">Embeddings File (Output)</label>
                    </td>
                    <td>
                        <input type="text" id="embeddings-file" name="embeddings-file" value="{{ current_config['embeddings_file'] }}">
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="index-heading-entries">Index Heading Entries</label>
                    </td>
                    <td>
                        <input type="text" id="index-heading-entries" name="index-heading-entries" value="{{ current_config['index_heading_entries'] }}">
                    </td>
                </tr>
            </table>
            <div class="section">
                <div id="success" style="display: none;" ></div>
                <button id="submit" type="submit">Save</button>
            </div>
        </form>
    </div>
</div>
<script>
    function addButtonEventListener(fieldName) {
        var button = document.getElementById(fieldName + "-button");
        button.addEventListener("click", function(event) {
            var cell = document.getElementById(fieldName + "-cell");
            var newInput = document.createElement("input");
            newInput.setAttribute("type", "text");
            newInput.setAttribute("name", fieldName);
            cell.appendChild(newInput);
        })
    }

    addButtonEventListener("input-files");
    addButtonEventListener("input-filter");

    function getValidInputNodes(nodes) {
        var validNodes = [];
        for (var i = 0; i < nodes.length; i++) {
            const nodeValue = nodes[i].value;
            if (nodeValue === "" || nodeValue === null || nodeValue === undefined || nodeValue === "None") {
                continue;
            }
            validNodes.push(nodes[i]);
        }
        return validNodes;
    }

    submit.addEventListener("click", function(event) {
        event.preventDefault();
        let globFormat = "**/*."
        let suffixes = [];
        if ('{{content_type}}' == "markdown")
            suffixes = ["md", "markdown"]
        else if ('{{content_type}}' == "org")
            suffixes = ["org"]
        else if ('{{content_type}}' === "pdf")
            suffixes = ["pdf"]
        else if ('{{content_type}}' === "plaintext")
            suffixes = ['*']

        var inputFileNodes = document.getElementsByName("input-files");
        var inputFiles = getValidInputNodes(inputFileNodes).map(node => node.value);

        var inputFilterNodes = document.getElementsByName("input-filter");

        var inputFilter = [];
        var nodes = getValidInputNodes(inputFilterNodes);
        if (nodes.length > 0) {
            for (var i = 0; i < nodes.length; i++) {
                for (var j = 0; j < suffixes.length; j++) {
                    inputFilter.push(nodes[i].value + globFormat + suffixes[j]);
                }
            }
        }

        if (inputFiles.length === 0 && inputFilter.length === 0) {
            alert("You must specify at least one input file or input filter.");
            return;
        }

        if (inputFiles.length == 0) {
            inputFiles = null;
        }

        if (inputFilter.length == 0) {
            inputFilter = null;
        }

        var compressed_jsonl = document.getElementById("compressed-jsonl").value;
        var embeddings_file = document.getElementById("embeddings-file").value;
        var index_heading_entries = document.getElementById("index-heading-entries").value;

        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        fetch('/api/config/data/content_type/{{ content_type }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({
                "input_files": inputFiles,
                "input_filter": inputFilter,
                "compressed_jsonl": compressed_jsonl,
                "embeddings_file": embeddings_file,
                "index_heading_entries": index_heading_entries
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data["status"] == "ok") {
                document.getElementById("success").innerHTML = "✅ Successfully updated. Go to your <a href='/config'>settings page</a> to complete setup.";
                document.getElementById("success").style.display = "block";
            } else {
                document.getElementById("success").innerHTML = "⚠️ Failed to update settings.";
                document.getElementById("success").style.display = "block";
            }
        })
    });
</script>
{% endblock %}
